<template>
    <div class="root" ref="root">
        <div class="flex-row">
            <div class="panel">
                <el-tree :data="tree_data" ref="tree" :props="{label:'name',children:'children'}" @node-click="handleNodeClick" @node-contextmenu="handleRightClick"/>
            </div>
            <div class="flex-full"><canvas id="canvas" ref="canvas"></canvas></div>
        </div>
        <div class="properties">
            <div>
                <div>属性</div>
                <el-row :gutter="20">
                    <el-col :span="1">x:</el-col>
                    <el-col :span="4">
                        <el-input type="number" v-model="properties.x" />
                    </el-col>
                    <el-col :span="1">y:</el-col>
                    <el-col :span="4">
                        <el-input type="number" v-model="properties.y" />
                    </el-col>
                </el-row>
                <!--<el-upload :action="uploadUrl"><el-button type="primary">上传</el-button></el-upload>-->
            </div>
        </div>
        <div>
            <el-button type="primary" @click="onSaveGame">保存游戏</el-button>
        </div>
    </div>
    <context-menu v-show="showContextMenu" ref="contextMenu" :data="menuList" v-clickOutSide="onClickOutSide"/>
    <el-dialog v-model="addImageDialogVisible" title="选择图片">
        <!-- <ImageList :imgList="imgList" @-picture-card-preview="handlePictureCardPreview" @remove-picture="handleRemove"/> -->
        <ImageTable @select-image="selectImage"/>
    </el-dialog>
    <el-dialog v-model="renameDialogVisible" title="图片命名" width="400">
        <el-form>
            <el-form-item label="图片名称">
                <el-input placeholder="请输入图片名称" v-model="rename"/>
            </el-form-item>
            <el-form-item label="图片路径">
                <el-image class="img" :src="baseUrl+imgModel.path" fit="contain"></el-image>
            </el-form-item>
        </el-form>
        <template #footer>
           <el-button @click="renameDialogVisible=false">取消</el-button>
           <el-button type="primary" @click="onSureRename">确定</el-button>
       </template>
    </el-dialog>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, watch,reactive } from 'vue'
import { useRoute } from 'vue-router';
import cjs=createjs
import { stageInit } from '@/utils/CreateJSHelper';
import GameRoot from '@/game/GameRoot';
import { DisplayObjectType, ViewEvent } from '@/const';
import BackgroundEditerView from '@/game/view/BackgroundEditerView';
import GameConfigModel from '@/game/model/GameConfigModel';
import ContextMenu from '@/components/ContextMenu.vue';
import LayerModel from '@/game/model/LayerModel';
import ImageModel from '@/game/model/ImageModel';
import { ElMessageBox, FormRules } from 'element-plus';
import DisplayObjectModel from '@/game/model/DisplayObjectModel';

export default defineComponent({
    name:'GameView',
    components:{
        ContextMenu
    },
    setup(){
        const baseUrl=process.env.VUE_APP_BASE_API
        const uploadUrl=ref(baseUrl+'/upload')
        //根节点
        const root=ref()
        //canvas节点
        const canvas=ref()
        //是否显示右键菜单
        const showContextMenu=ref(false)
        //添加图片弹窗
        const addImageDialogVisible=ref(false)
        //图片（动画）命名
        const renameDialogVisible=ref(false)
        //图片实例
        const imgModel=ref<ImageModel>()
        //右键菜单节点
        const contextMenu=ref()
        const tree_data=ref([])
        const properties=reactive({
            x:0,
            y:0
        })
        let main:GameRoot
        let stage:cjs.Stage
        let current_object:cjs.DisplayObject
        const gameMap:Map<string,GameRoot>=new Map()
        let scale=1
        const route = useRoute()
        //菜单数据
        const menuList=ref<any[]>([
            {name:'添加图片',call:():void=>{
                console.log('添加图片')
                addImageDialogVisible.value=true
            }},
            {name:'添加动画',call:():void=>{console.log('添加动画')}},
            {name:'添加主角',call:():void=>{
                console.log('添加主角')
                //
            }},
            {name:'添加容器',call:():void=>{console.log('添加容器')}},
            {name:'删除',call:():void=>{console.log('删除')}},
        ])
        //表单验证规则
        /*const renameRules=reactive<FormRules<any>>({
            name:[{
                required:true,
                message:'请输入图片名称',
                trigger: 'blur'
            }]
        })*/
        const rename=ref('')
        //当前选中的节点
        let current_tree_data:LayerModel
        //
        const onClickOutSide=()=>{
            showContextMenu.value=false
        }
        const onResize=()=>{
            const stageWidth=root.value.clientWidth
            canvas.value.width=stageWidth
            canvas.value.height=stageWidth*(1080/1920)
            scale=stageWidth/1920
            main.setTransform(0,0,scale,scale)
        }
        const handleNodeClick = (data: any) => {
            //console.log(data)
            properties.x=data.x
            properties.y=data.y
            current_object=data
        }
        onMounted(()=>{
            /*if(gameList.length==0){
                router.push('/')
                return
            }*/
            let id:string
            if(route.params.id instanceof Array){
                id=route.params.id[0]
            }else{
                id=route.params.id
            }
            if(gameMap.has(id)){
                main=gameMap.get(id)||new GameRoot(id)
            }else{
                main=new GameRoot(id)
                gameMap.set(id,main)
            }
            //main=gameMap.get(id)||new GameRoot(id)
            onResize()
            window.onresize=onResize
            stage=stageInit(canvas.value)
            stage.addChild(main)
            //stage.addEventListener('added',onAdded)
            //console.log('stage.on->ViewEvent.FLUSH_TREE')
            stage.on(ViewEvent.FLUSH_TREE,(e:cjs.Event)=>{
                //console.log(e)
                const view=e.target as BackgroundEditerView
                //console.log(view.getConfig())
                updateTree(view.getConfig())
            })
        })
        watch(()=>route.params.id,value=>{
            //console.log(value)
            let id:string
            if(value instanceof Array){
                id=value[0]
            }else{
                id=value
            }
            if(gameMap.has(id)){
                main=gameMap.get(id)||new GameRoot(id)
            }else{
                main=new GameRoot(id)
                gameMap.set(id,main)
            }
            onResize()
            stage.removeAllChildren()
            stage.addChild(main)
            //
            //updateTree()
        })
        watch(properties,()=>{
            //console.log(properties)
            if(!current_object)return
            current_object.x=properties.x
            current_object.y=properties.y
        })
        const updateTree=(model:GameConfigModel)=>{
            tree_data.value=model.layer
        }
        const handleRightClick=(e:PointerEvent,data:LayerModel)=>{
            console.log(data)
            current_tree_data=data
            e.preventDefault()
            showContextMenu.value=true
            //console.dir(unref(contextMenu))
            const style=contextMenu.value.$el.style
            style.left = e.clientX + 'px'
            style.top = e.clientY + 'px'
            //contextMenu.value.open(e.clientX,e.clientY)
        }
        const selectImage=(res)=>{
            console.log('selectImage',res)
            
            renameDialogVisible.value=true
            imgModel.value=ImageModel.create(res)
            /*return
            const model=new DisplayObjectModel()
            model.src=res.path
            model.type=DisplayObjectType.IMAGE
            main.send(ViewEvent.ADD_IMAGE,{parentName:current_tree_data.name,model})
            main.send(ViewEvent.FLUSH_EDITER)*/
        }
        const onSureRename=()=>{
            if(rename.value==''){
                ElMessageBox.alert('请输入图片名称', '错误',{
                    confirmButtonText: 'OK',
                    type: 'error'
                })
                return
            }
            addImageDialogVisible.value=false
            renameDialogVisible.value=false
            const model=new DisplayObjectModel()
            model.src=imgModel.value.path
            model.type=DisplayObjectType.IMAGE
            model.name=rename.value
            main.send(ViewEvent.ADD_IMAGE,{parentName:current_tree_data.name,model})
            main.send(ViewEvent.FLUSH_EDITER)
        }
        const onSaveGame=()=>{
            main.send(ViewEvent.SAVE_GAME)
        }
        return {
            root,
            canvas,
            tree_data,
            showContextMenu,
            contextMenu,
            properties,
            uploadUrl,
            menuList,
            addImageDialogVisible,
            renameDialogVisible,
            imgModel,
            baseUrl,
            rename,
            handleNodeClick,
            handleRightClick,
            onClickOutSide,
            selectImage,
            onSureRename,
            onSaveGame
        }
    }
})
</script>
<style scoped lang="less">
.root{
    #canvas{
        display: block;
        width: 100%;
        height: 100%;
    }
    .panel{
        width: 150px;
        height: 100%;
        background-color: #000000;
    }
    .properties{
        padding: 10px;
    }
}

</style>